package thread.java20230112;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用ReentrantLock 实现三个线程交替打印ABC
 */
public class Demo51 {
    static ReentrantLock lock = new ReentrantLock();
    //先创建三个唤醒的分组
    static Condition c1 = lock.newCondition();
    static Condition c2 = lock.newCondition();
    static Condition c3 = lock.newCondition();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 10; i++) {
               try {
                   lock.lock();
                   c1.await();//等待一个分组
                   c2.signal();//唤醒其他分组
                   System.out.println("A");
               }catch (Exception e){
                   e.printStackTrace();
               }finally {
                   lock.unlock();
               }
            }
        });

        Thread t2 = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    lock.lock();
                    c2.await();//等待一个分组
                    c3.signal();//唤醒其他分组
                    System.out.println("B");
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        });

        Thread t3 = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    lock.lock();
                    c3.await();//等待一个分组
                    c1.signal();//唤醒其他分组
                    System.out.println("C");
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        });

        t1.start();
        t2.start();
        t3.start();

        Thread.sleep(1000);//保证三个线程已经全部启动
        try {
            lock.lock();
            c1.signal();
        }finally {
            lock.unlock();
        }
    }



}
